const Koa = require("koa");
const Router = require("@koa/router");
const cors = require("koa2-cors");
const { koaBody } = require("koa-body"); // 引入 koa-body
const { exec } = require("child_process");
const app = new Koa();
const router = new Router();
/*
http://117.72.11.17:40061/i/2025/11/04/gvbcr2.png
http://117.72.11.17:40061/i/2025/11/04/gvbk2n.png
http://117.72.11.17:40061/i/2025/11/04/gvblnh.png
http://117.72.11.17:40061/i/2025/11/04/gvbl5c.png
*/

// 模拟商品数据
const mockProducts = [
  {
    id: 1,
    name: "超级爆款推荐露娜星慕黑",
    price: 688.00,
    sales_count: 1250,
    main_image: "http://117.72.11.17:40061/i/2025/11/04/gvbl5c.png",
    created_at: "2024-01-15T10:30:00Z",
    updated_at: "2024-01-15T10:30:00Z"
  },
  {
    id: 2,
    name: "超级爆款推荐露娜星慕黑",
    price: 688.00,
    sales_count: 890,
    main_image: "http://117.72.11.17:40061/i/2025/11/04/gvblnh.png",
    created_at: "2024-01-15T11:20:00Z",
    updated_at: "2024-01-15T11:20:00Z"
  },
  {
    id: 3,
    name: "超级爆款推荐露娜星慕黑",
    price: 688.00,
    sales_count: 2340,
    main_image: "http://117.72.11.17:40061/i/2025/11/04/gvbk2n.png",
    created_at: "2024-01-15T12:15:00Z",
    updated_at: "2024-01-15T12:15:00Z"
  },
  {
    id: 4,
    name: "超级爆款推荐露娜星慕黑",
    price: 688.00,
    sales_count: 2340,
    main_image: "http://117.72.11.17:40061/i/2025/11/04/gvbcr2.png",
    created_at: "2024-01-15T12:15:00Z",
    updated_at: "2024-01-15T12:15:00Z"
  },
  {
    id: 5,
    name: "超级爆款推荐露娜星慕黑",
    price: 688.00,
    sales_count: 2340,
    main_image: "http://117.72.11.17:40061/i/2025/11/04/gvbk2n.png",
    created_at: "2024-01-15T12:15:00Z",
    updated_at: "2024-01-15T12:15:00Z"
  },
  {
    id: 6,
    name: "超级爆款推荐露娜星慕黑",
    price: 688.00,
    sales_count: 2340,
    main_image: "http://117.72.11.17:40061/i/2025/11/04/gvbcr2.png",
    created_at: "2024-01-15T12:15:00Z",
    updated_at: "2024-01-15T12:15:00Z"
  }
];

/*
http://117.72.11.17:40061/i/2025/11/04/txuwdw.png
http://117.72.11.17:40061/i/2025/11/04/txuxiz.png
*/

// 模拟设备数据
const mockDevices = [
  {
    id: 1,
    name: "超级爆款推荐露娜星慕黑",
    remaining_battery: 90,
    is_connected: true,
    deviceId: "1234567890",
    image: "http://117.72.11.17:40061/i/2025/11/04/txuxiz.png"
  },
  {
    id: 2,
    name: "超级爆款推荐露娜星慕黑",
    remaining_battery: 19,
    is_connected: false,
    deviceId: "0987654321",
    image: "http://117.72.11.17:40061/i/2025/11/04/txuwdw.png"
  }
];

// 服务端支持跨域
app.use(
  cors({
    origin: "*", // 允许所有域名跨域
    credentials: true, // 允许跨域的时候带着 cookie
  })
);

// 使用 koa-body 中间件解析请求体
app.use(koaBody());

// 商品列表接口
router.get("/api/products", async (ctx) => {
  try {
    const { page = 1, limit = 10, keyword, sort } = ctx.query;
    
    let filteredProducts = [...mockProducts];
    
    // 关键词搜索
    if (keyword) {
      filteredProducts = filteredProducts.filter(product => 
        product.name.toLowerCase().includes(keyword.toLowerCase())
      );
    }
    
    // 排序
    if (sort) {
      switch (sort) {
        case 'price_asc':
          filteredProducts.sort((a, b) => a.price - b.price);
          break;
        case 'price_desc':
          filteredProducts.sort((a, b) => b.price - a.price);
          break;
        case 'sales_desc':
          filteredProducts.sort((a, b) => b.sales_count - a.sales_count);
          break;
        case 'created_desc':
          filteredProducts.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
          break;
      }
    }
    
    // 分页
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const startIndex = (pageNum - 1) * limitNum;
    const endIndex = startIndex + limitNum;
    const paginatedProducts = filteredProducts.slice(startIndex, endIndex);
    
    ctx.body = {
      code: 200,
      message: "success",
      data: {
        list: paginatedProducts,
        pagination: {
          current_page: pageNum,
          per_page: limitNum,
          total: filteredProducts.length,
          total_pages: Math.ceil(filteredProducts.length / limitNum)
        }
      }
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: "服务器内部错误",
      data: null
    };
  }
});

// 设备列表接口（无分页、无筛选）
router.get("/api/devices", async (ctx) => {
  try {
    ctx.body = {
      code: 200,
      message: "success",
      data: mockDevices
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: "服务器内部错误",
      data: null
    };
  }
});

// 新增 /api/list 接口
router.get("/api/list", async (ctx) => {
  try {
    ctx.body = {
      "total": 1,
      "rows": [
        {
          "id": "1986320757580091394",
          "createBy": "admin",
          "createTime": "2025-11-06 14:32:27",
          "updateBy": "admin",
          "updateTime": "2025-11-06 14:32:27",
          "title": "双肩包",
          "originalPrice": "1000",
          "discountPrice": "500",
          "picUrl": "https://oss.gyxx.cn/admin/commodity/17624107233707U6A2525.JPG",
          "wxUrl": "https://j.youzan.com/ucRNA_",
          "status": 1,
          "sort": null
        },
        {
          "id": "1986320757580091395",
          "createBy": "admin",
          "createTime": "2025-11-06 14:32:27",
          "updateBy": "admin",
          "updateTime": "2025-11-06 14:32:27",
          "title": "双肩包",
          "originalPrice": "1000",
          "discountPrice": "500",
          "picUrl": "https://oss.gyxx.cn/admin/commodity/17624107233707U6A2525.JPG",
          "wxUrl": "https://j.youzan.com/ucRNA_",
          "status": 1,
          "sort": null
        },
        {
          "id": "1986320757580091396",
          "createBy": "admin",
          "createTime": "2025-11-06 14:32:27",
          "updateBy": "admin",
          "updateTime": "2025-11-06 14:32:27",
          "title": "双肩包",
          "originalPrice": "1000",
          "discountPrice": "500",
          "picUrl": "https://oss.gyxx.cn/admin/commodity/17624107233707U6A2525.JPG",
          "wxUrl": "https://j.youzan.com/ucRNA_",
          "status": 1,
          "sort": null
        },
        {
          "id": "1986320757580091397",
          "createBy": "admin",
          "createTime": "2025-11-06 14:32:27",
          "updateBy": "admin",
          "updateTime": "2025-11-06 14:32:27",
          "title": "双肩包",
          "originalPrice": "1000",
          "discountPrice": "500",
          "picUrl": "https://oss.gyxx.cn/admin/commodity/17624107233707U6A2525.JPG",
          "wxUrl": "https://j.youzan.com/ucRNA_",
          "status": 1,
          "sort": null
        }
      ],
      "code": 200,
      "msg": "查询成功"
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: "服务器内部错误",
      data: null
    };
  }
});
// 用户信息接口
router.get("/api/user-info", async (ctx) => {
  try {
    ctx.body = {
      "msg": "操作成功",
      "code": 200,
      "data": {
        "userId": 1963917962088747010,
        "username": "uname",
        "phone": "12345678910",
        "nickname": "老刘得到111555fhhh",
        "avatar": "https://oss.gyxx.cn/app/avatar/1760857788-1760857788056.jpg",
        "gender": "male",
        "birthday": "2024-09-12",
        "loginTime": 1763201019639,
        "expireTime": 38051201019639,
        "ipaddr": "14.112.71.13",
        "loginLocation": "XX XX",
        "os": "Unknown",
        "version": null,
        "token": "",
        "first": false
      }
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: "服务器内部错误",
      data: null
    };
  }
});

// 自动部署
router.post("/webhook", async (ctx) => {
  ctx.body = { success: true, message: "部署已开始!" };
  setTimeout(() => {
    exec("/www/wwwroot/pure-koa/deploy.sh", (error, stdout, stderr) => {
      if (error) {
        console.error(`${new Date().toLocaleString()} ❌ 部署失败:`, error.message);
        console.error(stderr);
      } else {
        console.log(`${new Date().toLocaleString()} ✅ 部署成功:\n`, stdout);
      }
    });
  }, 1000);
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(9001, () => console.log(`${new Date().toLocaleString()} 🚀 http://localhost:9001`));
